<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
    <div class="hearder-search">
      <el-col :span="24" class="breadcrumb-container button-line">
        <!--<el-button type="primary" @click.native="addBook" size="small">选择导入的Excel文件</el-button>-->
        <el-upload ref="upload" action="/" :show-file-list="false" :on-change="importExcel" :auto-upload="false">
          <el-button slot="trigger" icon="el-icon-upload" size="small" type="primary"> 选择导入的图书Excel文件 </el-button>
        </el-upload>
        <el-button type="success" @click.native="addBook" size="small" class="addexcel">确定导入Excel文件数据</el-button>
        <!--<el-button type="primary" size="small">回收站</el-button>-->
        <el-button size="small" @click="refreshFn"><i class="el-icon-refresh"></i>刷新</el-button>
      </el-col>
    </div>
    <!--本体列表，数据 -->
    <div class="table-body">
      <div class="table-body-box">
        <el-table
                ref="multipleTable"
                :data="arryList"
                :stripe="tableStripe"
                :border="tableBorder"
                tooltip-effect="dark"
                style="width: 100%"
                header-cell-class-name="table-text-c"
                cell-class-name="table-text-c"
                :height="tableHeight">
          <el-table-column
                  type="index"
                  label="序号"
                  width="50">
          </el-table-column>
          <!--{'书名': 'name', '位置': 'position', '库存': 'num', '条码': 'barcode', '作者': 'editor', '价格': 'press'}-->
          <el-table-column
                  prop="name"
                  label="书名">
          </el-table-column>
          <el-table-column
                  prop="position"
                  label="位置"
                  width="70">
          </el-table-column>
          <el-table-column
                  prop="num"
                  label="库存"
                  width="70">
          </el-table-column>
          <el-table-column
                  prop="barcode"
                  label="条码"
                  width="150">
          </el-table-column>
          <el-table-column
                  prop="editor"
                  label="作者"
                  width="80">
          </el-table-column>
          <el-table-column
                  prop="press"
                  label="价格"
                  width="80">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--工具条 分页-->
    <!--<el-col :span="24" class="toolbar">-->
      <!--<el-pagination-->
              <!--background-->
              <!--layout="prev, pager, next"-->
              <!--:total="pageTotal"-->
              <!--:page-size="pageSize"-->
              <!--:current-page="page"-->
              <!--@current-change="handleSizeChange">-->
      <!--</el-pagination>-->
    <!--</el-col>-->
    <!--编辑界面-->
  </div>
  </div>
</template>

<script>
  import XLSX from 'xlsx'

  export default {
    data () {
      return {
        tableStripe: true, // 是否斑马栏
        tableBorder: true, // 单元格右边边框
        searchWord: '', // 搜索名称
        editLoading: false, // 编辑界面按键缓存
        tieleName: '',
        tableHeight: 100,
        page: 1,
        pageSize: 20,
        pageTotal: 0, // 总页数
        arryList: []
      }
    },
    created () {
      this.InitFn()
    },
    methods: {
      InitFn () {
        // this.tableHeight = window.innerHeight - this.$refs.multipleTable.$el.offsetTop - 200
      },
      // 分页
      handleSizeChange (val) {
        this.page = val
        console.log(val)
      },
      // 刷新页面
      refreshFn () {
        this.arryList = []
      },
      importExcel (file) {
        // let file = file.files[0] // 使用传统的input方法需要加上这一步
        let self_ = this
        const types = file.name.split('.')[1]
        const fileType = ['xlsx', 'xlc', 'xlm', 'xls', 'xlt', 'xlw', 'csv'].some(item => item === types)
        if (!fileType) {
          this.$message('格式错误！请重新选择')
          return
        }
        let title = {'书名': 'name', '位置': 'position', '库存': 'num', '条码': 'barcode', '作者': 'editor', '价格': 'press'}
        let arrayList = []
        this.file2Xce(file).then(tabJson => {
          console.log('输出数据内容file2Xce：', tabJson)
          if (tabJson && tabJson.length > 0) {
            this.xlsxJson = tabJson
            console.log('数据', this.xlsxJson)
            let xlseJsonLsit = this.xlsxJson[0].sheet
            for (let i = 0; i < xlseJsonLsit.length; i++) {
              let titleline = {}
              for (let j in title) {
                titleline[title[j]] = xlseJsonLsit[i][j]
              }
              arrayList.push(titleline)
            }
            self_.pageTotal = arrayList.length
            self_.arryList = arrayList
            this.tableHeight = window.innerHeight - this.$refs.multipleTable.$el.offsetTop - 100
            console.log('数据整理', arrayList)
          }
        })
      },
      file2Xce (file) {
        return new Promise(function (resolve, reject) {
          const reader = new FileReader()
          reader.onload = function (e) {
            const data = e.target.result
            this.wb = XLSX.read(data, {
              type: 'binary'
            })
            const result = []
            this.wb.SheetNames.forEach((sheetName) => {
              console.log('sheetName：', sheetName)
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
              })
            })
            resolve(result)
          }
          reader.readAsBinaryString(file.raw)
          // reader.readAsBinaryString(file) // 传统input方法
        })
      },
      addBook () {
        if (this.arryList.length !== 0) {
          console.log('确认导入数据')
          this.$post('book/importall', {data: JSON.stringify(this.arryList)}).then((response) => {
            console.log(response)
            if (response.code === 0) {
            } else {
              console.log('请求失败')
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          this.$message.error('请选择导入的Excel文件')
        }
      }
    },
    mounted () {
      console.log('表格距离浏览器可用高度顶部的距离', this.$refs.multipleTable.$el.offsetTop)
      console.log('计算table高度：', window.innerHeight - this.$refs.multipleTable.$el.offsetTop)
      // this.tableHeight = window.innerHeight - this.$refs.multipleTable.$el.offsetTop - 110
      // this.clientHeight = document.body.clientHeight
      const _this = this
      window.onresize = function temp () {
        console.log('屏幕高度:', window.innerHeight - _this.$refs.multipleTable.$el.offsetTop - 200)
        _this.tableHeight = window.innerHeight - _this.$refs.multipleTable.$el.offsetTop - 200
      }
    }
  }
</script>

<style lang="scss">
  .addexcel{
    margin-left:10px;
  }
  .outputlist_upload {
    width: 100px !important;
  }

  #tablebox {
    display: flex;
    flex-direction: column;
  }

  .el-table {
    color: #000;
  }

  .right-box .container .main .content-container .input-val-box .input-top {
    width: 250px;
  }

  .hearder-search {
    overflow: hidden;
  }

  .toolbar {
    text-align: center;
  }


  .bookname {
    color: #42b983;
  }

  .canborrow {
    color: #67C23A
  }

  .notborrow {
    color: #F56C6C
  }
</style>
